package com.jinlejia.erp.ui.house;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;

import androidx.appcompat.app.AppCompatActivity;
import androidx.databinding.DataBindingUtil;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.jinlejia.erp.R;
import com.jinlejia.erp.base.ApiConfig;
import com.jinlejia.erp.base.MapCallBack;
import com.jinlejia.erp.bean.SaveCookieBean;
import com.jinlejia.erp.databinding.ActivityHouseDetailBinding;
import com.jinlejia.erp.ui.common.ContactDialog;
import com.jinlejia.erp.ui.common.GuideDialog;
import com.jinlejia.erp.ui.common.ProgressDialog;
import com.jinlejia.erp.ui.common.ShareDialog;
import com.jinlejia.erp.ui.house.prospect.ProspectIndexActivity;
import com.jinlejia.erp.ui.house.prospect.ProspectReplenishActivity;
import com.jinlejia.erp.ui.house.prospect.Type;
import com.jinlejia.erp.utils.ACache;
import com.jinlejia.erp.utils.CallUtils;
import com.jinlejia.erp.utils.DataFilter;
import com.jinlejia.erp.utils.DbUtil;
import com.weight.CustomToast;
import com.zhy.http.okhttp.OkHttpUtils;

import org.simple.eventbus.EventBus;

import java.util.ArrayList;
import java.util.Map;

import okhttp3.Call;
import okhttp3.MediaType;
import rx.Observable;
import rx.android.schedulers.AndroidSchedulers;

public class HouseDetailActivity extends AppCompatActivity {

    ContactDialog contactDialog;
    private String type, code, phoneNO = "", shsType = "";

    private String isFirst = "1";
    private String url = null;
    private String url_icon = ApiConfig.HEADER_URL() + "T1doxVB4CT1RXrhCrK.jpg";

    private ProgressDialog progressDialog;
    private ShareDialog shareDialog;
    private ShareInfo mShareInfo; //分享对话框的数据
    private ArrayList<Map<String, Object>> mImgList;

    private ActivityHouseDetailBinding binding;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = DataBindingUtil.setContentView(this, R.layout.activity_house_detail);


        binding.btBack.setOnClickListener(this::onClick);
        binding.btCollect.setOnClickListener(this::onClick);
        binding.btShare.setOnClickListener(this::onClick);
        binding.llFollow.setOnClickListener(this::onClick);
        binding.llContact.setOnClickListener(this::onClick);
        binding.llInvestigation.setOnClickListener(this::onClick);


        type = getIntent().getStringExtra("type");
        code = getIntent().getStringExtra("code");

        progressDialog = new ProgressDialog(this, "加载中...");
        if (type.equals("shs") || type.equals("sale")) {
            //出售房源详情
            getShsData();
        } else {
            //出租房源详情
            getRentData();
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        //指引弹出层
        if (TextUtils.isEmpty(ACache.get(this).getAsString("house_detail_guide")))
            new GuideDialog(this, "house_detail_guide", R.mipmap.guide_house_detail).show();
    }

    private void getShsData() {
        progressDialog.show();
        OkHttpUtils.get()
                .url(ApiConfig.Sell_HOUSE_DETAIL.concat(code))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HouseDetailActivity.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString()).getJSONObject("shsDetailResult");
                            parseData(data);
                            EventBus.getDefault().post(data, "TAG_SHS_DATA");
                        }
                    }
                });
    }

    private void getRentData() {
        progressDialog.show();
        OkHttpUtils.get()
                .url(ApiConfig.RENT_HOUSE_DETAIL.concat(code))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (null != progressDialog && progressDialog.isShowing()) {
                            progressDialog.dismiss();
                        }
                        if (DataFilter.filter(HouseDetailActivity.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString()).getJSONObject("rentDetailResult");
                            parseData(data);
                            EventBus.getDefault().post(data, "TAG_RENT_DATA");
                        }
                    }
                });
    }

    //查看核心
    private void checkCore(String url) {
        final String url1 = url.concat(code);
        Observable.create((Observable.OnSubscribe<Map<String, Object>>) subscriber -> OkHttpUtils.get()
                .url(url1)
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        subscriber.onNext(response);
                        subscriber.onCompleted();
                    }
                })).subscribeOn(AndroidSchedulers.mainThread())
                .subscribe(response -> {
                    if (DataFilter.filter(HouseDetailActivity.this, response)) {
                        JSONObject data = JSON.parseObject(response.get("data").toString());
                        if (data.containsKey("tel"))
                            phoneNO = data.get("tel").toString();
                        String coreCount = "";
                        if (data.containsKey("coreCount"))
                            coreCount = data.getString("coreCount");
                        contactDialog = new ContactDialog(HouseDetailActivity.this, data);
                        contactDialog.setOnCallListener(new ContactDialog.OnCallListener() {
                            @Override
                            public void call(String tel) {
                                if (null != contactDialog && contactDialog.isShowing())
                                    contactDialog.dismiss();
                                CallUtils.CallTel(HouseDetailActivity.this, tel);

                            }
                        });
                        if (Integer.parseInt(coreCount) <= 5) {
                            if (null != contactDialog)
                                contactDialog.show();
                        } else {
                            CustomToast.showToast(HouseDetailActivity.this, "今日查看核心次数上限", 1500);
                        }

                    }
                });

    }


    private void parseData(JSONObject object) {
        //region 缓存房源的一些信息给 @link{ProspectIndexActivity} 使用
        //TIME 2018年12月26日
        //AUTHOR 王进
        this.houseType = object.getString("houseType"); //房屋户型
        this.purpose = object.getString("purpose"); //房屋用途
        this.estate = object.getString("estate"); //房屋所属小区名称
        //endregion

        if (object.containsKey("isFirst"))
            isFirst = object.get("isFirst").toString();
        if (object.get("isAtten").toString().equals("0")) {
            //未关注
            binding.btCollect.setImageResource(R.mipmap.ic_collect);
            binding.btCollect.setTag(0);
        } else {
            //已关注
            binding.btCollect.setImageResource(R.mipmap.ic_has_collect);
            binding.btCollect.setTag(1);
        }
        binding.houseName.setText(object.getString("estate"));
        shsType = object.getString("shsType");
        if (!TextUtils.isEmpty(shsType)) {
            if (type.equals("shs")) {
                //出售房源
                if (shsType.equals("0")) {
                    //私盘查看核心
                    url = ApiConfig.SHS_SELF_CORE;
                } else if (shsType.equals("1")) {
                    //公盘查看核心
                    url = ApiConfig.SHS_ALL_CORE;
                } else if (shsType.equals("2")) {
                    //特盘查看核心
                    url = ApiConfig.SHS_SEP_CORE;
                } else if (shsType.equals("7")) {
                    //成交查看核心
                    url = ApiConfig.SHS_STATE_CORE;
                }
            } else {
                //出租房源
                if (shsType.equals("0")) {
                    //私盘查看核心
                    url = ApiConfig.RENT_SELF_CORE;
                } else if (shsType.equals("1")) {
                    //公盘查看核心
                    url = ApiConfig.RENT_ALL_CORE;
                } else if (shsType.equals("2")) {
                    //特盘查看核心
                    url = ApiConfig.RENT_SEP_CORE;
                } else if (shsType.equals("7")) {
                    //成交查看核心
                    url = ApiConfig.RENT_STATE_CORE;
                }
            }
        }

        //楼层
        String floor = "";
        if (object.containsKey("floorType")) {
            if (object.get("floorType").toString().equals("1")) {
                floor = "低楼层";
            } else if (object.get("floorType").toString().equals("2")) {
                floor = "中楼层";
            } else if (object.get("floorType").toString().equals("3")) {
                floor = "高楼层";
            }
        }
        String content;
        String url;
        String smsBody;
        /*
         * TIME：2017-9-6
         * BUGID: 2386
         * MODIFIER: 王彤
         * MODIFY: 修改内容  户型 3-1-1-0 改为 3室1厅1卫0台
         */
        String s = object.getString("houseType");


        String houseType = "";
        String subject;
        if (!s.equals("0-0-0-0") && !TextUtils.isEmpty(s)) {
            houseType = s.replaceFirst("-", "室").replaceFirst("-", "厅").replaceFirst("-", "厨").concat("卫");
        }
        if (!TextUtils.isEmpty(houseType)) {
            subject = object.getString("estate").concat("  ,  ").concat(houseType);
        } else {
            subject = object.getString("estate");
        }
        if (type.equals("shs")) {
            content = "报价".concat(object.getString("salePrice"))+"万"+"面积".concat(object.getString("square"))+"㎡"
                    .concat("楼层:").concat(floor).concat(";朝向:").concat(object.getString("face"));
            url = String.format("http://m.jinlejia.com/shs/detail.action?rscode=%s&pin=%s", code, DbUtil.getDB(HouseDetailActivity.this).single().queryById(202, SaveCookieBean.class).getPin());
            smsBody = subject.concat(";").concat(object.getString("square"))
                    .concat("㎡;").concat(floor).concat(";").concat(object.getString("face"));
        } else {
            content = "租金:".concat(object.getString("salePrice")).concat("元/月;面积:").concat(object.getString("square"))
                    .concat("㎡;楼层:").concat(floor).concat(";朝向:").concat(object.getString("face"));
            url = String.format("http://m.jinlejia.com/rent/detail.action?rscode=%s&pin=%s", code, DbUtil.getDB(HouseDetailActivity.this).single().queryById(202, SaveCookieBean.class).getPin());
            smsBody = subject.concat(";").concat(object.getString("salePrice")).concat("元/月;").concat(object.getString("square"))
                    .concat("㎡;").concat(floor).concat(";").concat(object.getString("face"));
        }
        mImgList = JSON.parseObject(object.getJSONArray("imgList").toString(), new TypeReference<ArrayList<Map<String, Object>>>() {
        });
        String imgUrl = ApiConfig.MAGEHEADER_URL();
        if (mImgList.size() > 0) {
            imgUrl += mImgList.get(0).get("imgUrl").toString();
        }
        smsBody = smsBody.concat(" ，详情：").concat(url).concat("。来自【进了家】");
        /*
         * 不能够在此创建ShareDialog，因为在ShareDialog中创建了微信广播。
         * 并且在创建后，长时间不取消广播，会造成部分手机崩溃闪退。
         * 所以改用创建一个对象来存储ShareDialog所需要的对象
         */
        mShareInfo = new ShareInfo(subject, content, smsBody, "", imgUrl, R.drawable.ic_share_house, url, url_icon);

    }


    private static class ShareInfo {
        private String subject;
        private String content;
        private String smsBody;
        private String smsTo;
        private String imgUrl;
        private int icon;
        private String url;
        private String urlIcon;

        public ShareInfo(String subject, String content, String smsBody, String smsTo, String imgUrl, int icon, String url, String urlIcon) {
            this.subject = subject;
            this.content = content;
            this.smsBody = smsBody;
            this.smsTo = smsTo;
            this.imgUrl = imgUrl;
            this.icon = icon;
            this.url = url;
            this.urlIcon = urlIcon;
        }
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.bt_back:
                finish();
                break;
            case R.id.bt_collect:
                //收藏
                addAtten();
                break;
            case R.id.bt_share:
                //分享
                if (type.equals("shs")) {
                    //出售房源
                    if (shareDialog == null && mShareInfo != null) {
                        shareDialog = new ShareDialog(this, mShareInfo.subject, mShareInfo.content, mShareInfo.smsBody, mShareInfo.smsTo,
                                mShareInfo.imgUrl, mShareInfo.icon, String.format("https://m.jinlejia.com/shs/detail.action?rscode=%s&pin=%s", code, DbUtil.getDB(HouseDetailActivity.this).single().queryById(202, SaveCookieBean.class).getPin()), mShareInfo.urlIcon);
                    }
                    if (shareDialog != null)
                        shareDialog.show();
                } else {
                    //出租房源
                    if (shareDialog == null && mShareInfo != null) {
                        shareDialog = new ShareDialog(this, mShareInfo.subject, mShareInfo.content, mShareInfo.smsBody, mShareInfo.smsTo,
                                mShareInfo.imgUrl, mShareInfo.icon, mShareInfo.url, mShareInfo.urlIcon);
                    }
                    if (shareDialog != null)
                        shareDialog.show();
                }
                break;
            case R.id.ll_follow:
                //跟进
                Intent followIntent = new Intent(HouseDetailActivity.this, HouseFllowActivity.class);
                followIntent.putExtra("code", code);
                followIntent.putExtra("type", type);
                startActivity(followIntent);
                break;
            case R.id.ll_contact:
                //联系业主
                if (TextUtils.isEmpty(shsType)) {
                    CustomToast.showToast(HouseDetailActivity.this, "该房源不能查看核心", 1500);
                } else {
                    checkCore(url);
                }
                break;
            case R.id.ll_investigation://实勘
                checkProspectFormServer(type);
                break;
            default:
                break;
        }
    }

    private String estate = null; //小区名称
    private String houseType = null; //户型信息 格式为3-2-1-0 含义为：3室2厅1卫0台
    private String purpose = null; //房屋用途

    /**
     * 跳转至 实勘图片上传引导页
     *
     * @param type     跳页 1:新增 2:修改 3:补充
     * @param isReason true:需要填写顶替理由 false:other
     * @author 王进
     * @date 2018年12月26日
     */
    private void toProspectIndexActivity(int type, boolean isReason) {
        Intent intent = new Intent();
        if (type == 3) { //补充时
            intent.setClass(this, ProspectReplenishActivity.class);
        } else { //新增或者修改
            intent.setClass(this, ProspectIndexActivity.class);
        }

        intent.putExtra(Type.PARAM.HOUSE_TYPE, houseType); //房屋户型
        intent.putExtra(Type.PARAM.PAGE_TYPE, type); //跳页
        intent.putExtra(Type.PARAM.HOUSE_SOURCE_CODE, this.code); //房源编码
        intent.putExtra(Type.PARAM.HOUSE_SOURCE_TYPE, this.type); //房源类型
        intent.putExtra(Type.PARAM.HOUSE_USAGE_NAME, this.purpose);   //房屋用途
        intent.putExtra(Type.PARAM.REASON, isReason); //是否需要填写顶替理由
        startActivityForResult(intent, 100);
    }

    /**
     * 检查图片上传方式从服务器
     *
     * @param checkType shs: 出售 other: 出租
     */
    private void checkProspectFormServer(String checkType) {
        String url;
        if ("shs".equals(checkType)) { //出售房源详情
            url = ApiConfig.PROSPECT_SHS_CHECK;
        } else { //出租房源详情
            url = ApiConfig.PROSPECT_RENT_CHECK;
        }
        OkHttpUtils.get()
                .url(url.concat(code))
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(HouseDetailActivity.this, response)) {
                            JSONObject data = JSON.parseObject(response.get("data").toString());
                            //跳页 1:新增 2:修改 3:补充
                            int type = Integer.parseInt(String.valueOf(data.get("type")));
                            //是否需要填写顶替理由 1:是 2:否
                            boolean isReason = Integer.parseInt(String.valueOf(data.get("isReason"))) == 1;
                            if (houseType == null) return; //当房屋类型没有获取到时，直接返回
                            toProspectIndexActivity(type, isReason);
                        }
                    }
                });
    }

    private void addAtten() {
        String url;
        if (type.equals("shs")) {
            //出售房源
            url = ApiConfig.SHS_ATTEN;
        } else {
            //出租房源
            url = ApiConfig.RENT_ATTEN;
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("rscode", code);
        OkHttpUtils.postString()
                .url(url)
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .content(jsonObject.toString())
                .build()
                .execute(new MapCallBack() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        e.printStackTrace();
                    }

                    @Override
                    public void onResponse(Map<String, Object> response, int id) {
                        if (DataFilter.filter(HouseDetailActivity.this, response)) {
                            //成功
                            if (binding.btCollect.getTag().toString().equals("0")) {
                                binding.btCollect.setImageResource(R.mipmap.ic_has_collect);
                                binding.btCollect.setTag(1);
                                CustomToast.showToast(HouseDetailActivity.this, "关注成功", 1500);
                            } else {
                                binding.btCollect.setImageResource(R.mipmap.ic_collect);
                                binding.btCollect.setTag(0);
                                CustomToast.showToast(HouseDetailActivity.this, "取消成功", 1500);
                            }
                        }

                    }
                });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 100) { //当上传实勘信息完成时，更新房源数据
                if (type.equals("shs") || type.equals("sale")) {
                    //出售房源详情
                    getShsData();
                } else {
                    //出租房源详情
                    getRentData();
                }
            }
        }
    }

    @Override
    protected void onDestroy() {
        if (null != progressDialog && progressDialog.isShowing()) {
            progressDialog.dismiss();
        }
        if (null != contactDialog && contactDialog.isShowing())
            contactDialog.dismiss();
        super.onDestroy();
    }
}
